using System;
using System.IO;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media.Imaging;

namespace Intuipic.Converters
{
	/// <summary>
	/// A converter used to automatically orient a picture based on orientation metadata embedded in the image.
	/// </summary>
	/// <remarks>
	/// Refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values.
	/// </remarks>
	public sealed class BitmapOrientationConverter : IValueConverter
	{
		private const string _orientationQuery = "System.Photo.Orientation";

		public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			string path = value as string;

			if (path != null)
			{
				using (FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read))
				{
					BitmapFrame bitmapFrame = BitmapFrame.Create(fileStream, BitmapCreateOptions.DelayCreation, BitmapCacheOption.None);
					BitmapMetadata bitmapMetadata = bitmapFrame.Metadata as BitmapMetadata;

					if ((bitmapMetadata != null) && (bitmapMetadata.ContainsQuery(_orientationQuery)))
					{
						object o = bitmapMetadata.GetQuery(_orientationQuery);

						if (o != null)
						{
							//refer to http://www.impulseadventure.com/photo/exif-orientation.html for details on orientation values
							switch ((ushort) o)
							{
								case 6:
									return 90D;
								case 3:
									return 180D;
								case 8:
									return 270D;
							}
						}
					}
				}
			}

			return DependencyProperty.UnsetValue;
		}

		public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
		{
			return DependencyProperty.UnsetValue;
		}
	}
}
